local xserver = {}

print("====XConsole Server, a LUA console over wifi.======")
print("Author: openthings@163.com. copyright&GPL V2.")
print("starting...2014-12-04. V0.31. HEAP:"..node.heap())

tCount=0
tBreak=0
tStatus=0
apIndex=1
apMax=2
who="ESP8266_SMARTLUMP"

local apTable={
{"HiWiFi_SMT","87654321","192.168.199.200"},
{"NETGEAR71","shinyphoenix155","192.168.1.100"}}

function xserver.who()
	print(who)
end

function xserver.apl()
	for i=1,#apTable do
		print("SSID:"..apTable[i][1]..","..apTable[i][2])
	end
end

function xserver.ondata(sdata)
	--print(data)
end

function xserver.startServer()
    if wifi.sta.getip()==nil then
        print("Wifi AP not invalid.")
    else
        print("Wifi AP connected. Server IP:")
	sv=net.createServer(net.TCP,3600)
	sv:listen(8080,	function(conn)
		print("Wifi console connected.")
		function s_output(str)
			if (conn~=nil) then conn:send(str) end
		end
		node.output(s_output,1)

		conn:on("receive", function(conn, pl) 
			node.input(pl) 
			if (conn==nil) 	then print("conn is nil.") end
		end)
		conn:on("disconnection",function(conn) 
			node.output(nil) 
		end)
	end)	
	print("xconsole Server running at: 8080,Heap: "..node.heap())
    end
end

function xserver.checkIP()
	if tBreak==1 then tmr.stop(0) end
	if wifi.sta.getip()==nil then
		if (tStatus==1) then 
			tStatus=0
			--net.server.close()
			tmr.alarm(0,2000, 1, xserver.checkIP)
		end
		print(string.format("%d:Connect AP, Waiting...",tCount)) 
		tCount=tCount+1
		if tCount>5 then
			print("Trying SSID:"..apTable[apIndex][1]..","..apTable[apIndex][2])
			wifi.setmode(wifi.STATIONAP)
			wifi.sta.config(apTable[apIndex][1],apTable[apIndex][2])
			wifi.sta.connect()
			tCount=0
			apIndex = apIndex+1
			if apIndex>apMax then
				apIndex=1
			end
		end
	else
		if tStatus==0 then
			xserver.startServer()
			tmr.alarm(0,5000, 1, xserver.checkIP)
			tStatus = 1
		else
			print("*Tic: ["..tmr.now().."] Wifi AP OK. Server IP:"..wifi.sta.getip())
		end
	end
end

function xserver.waitstart()
	tmr.alarm(0,2000, 1, xserver.checkIP)
end

--xserver.waitstart()

return xserver
